<template>
  <el-dialog
    class="nodeFileDialog"
    title="插入文件"
    v-model="dialogVisible"
    width='600px'
    top='15vh'
  >
    <div class="fileUploadContainer">
      <div class="uploadArea" v-if="!uploadedFile">
        <el-upload
          ref="uploadRef"
          action="xxxx"
          :accept="'.doc,.docx,.xls,.xlsx,.pdf'"
          :show-file-list="false"
          :before-upload="beforeUpload"
          :on-success="onUploadSuccess"
          :on-error="onUploadError"
          :disabled="uploading"
        >
          <el-button type="primary" :loading="uploading">
            {{ uploading ? '上传中...' : '选择文件' }}
          </el-button>
        </el-upload>
        <div class="tip">支持格式：Word、Excel、PDF</div>
      </div>
      
      <div class="fileInfo" v-if="uploadedFile">
        <div class="fileName">
          <i class="el-icon-document"></i>
          {{ uploadedFile.name }}
        </div>
        <div class="fileUrl">{{ uploadedFile.url }}</div>
        <el-button size="small" @click="removeFile">重新选择</el-button>
      </div>
    </div>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancel">{{ $t('dialog.cancel') }}</el-button>
        <el-button 
          type="primary" 
          @click="confirm"
          :disabled="!uploadedFile"
        >
          {{ $t('dialog.confirm') }}
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { useI18n } from 'vue-i18n'
import { useEventBus } from '@/hooks'
import { isMobile } from 'simple-mind-map/src/utils/index'
import { ElMessage } from 'element-plus'

// 组合式API设置
const { t } = useI18n()
const { $on, $off, $emit, $once } = useEventBus()

// 响应式数据
const dialogVisible = ref(false)
const activeNodes = ref(null)
const isMobileDevice = ref(isMobile())
const uploading = ref(false)
const uploadedFile = ref(null)

// 模板引用
const uploadRef = ref(null)

// 生命周期钩子
onMounted(() => {
  $on('node_active', handleNodeActive)
  $on('showNodeFile', handleShowNodeFile)
})

onBeforeUnmount(() => {
  $off('node_active', handleNodeActive)
  $off('showNodeFile', handleShowNodeFile)
})

// 方法
const handleNodeActive = (...args) => {
  activeNodes.value = [...args[1]]
}

const handleShowNodeFile = () => {
  reset()
  if (activeNodes.value.length > 0) {
    let firstNode = activeNodes.value[0]
    let fileData = firstNode.getData('fileUrl')
    let fileName = firstNode.getData('fileName')
    if (fileData && fileName) {
      uploadedFile.value = {
        name: fileName,
        url: fileData
      }
    }
  }
  dialogVisible.value = true
}

const beforeUpload = (file) => {
  const allowedTypes = [
    'application/msword',
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    'application/vnd.ms-excel',
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    'application/pdf'
  ]
  
  const allowedExtensions = ['.doc', '.docx', '.xls', '.xlsx', '.pdf']
  const fileName = file.name.toLowerCase()
  const isValidType = allowedExtensions.some(ext => fileName.endsWith(ext))
  
  if (!isValidType) {
    ElMessage.error('只支持Word、Excel、PDF格式的文件！')
    return false
  }
  
  const isLt10M = file.size / 1024 / 1024 < 10
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过10MB！')
    return false
  }
  
  uploading.value = true
  return true
}

const onUploadSuccess = (response, file) => {
  uploading.value = false
  // 假设服务器返回格式为 { url: 'http://xxx.com/file.pdf' }
  if (response && response.url) {
    uploadedFile.value = {
      name: file.name,
      url: response.url
    }
    ElMessage.success('文件上传成功！')
  } else {
    ElMessage.error('文件上传失败，请重试！')
  }
}

const onUploadError = (error) => {
  uploading.value = false
  ElMessage.error('文件上传失败，请重试！')
  console.error('Upload error:', error)
}

const removeFile = () => {
  uploadedFile.value = null
}

const cancel = () => {
  dialogVisible.value = false
  reset()
}

const reset = () => {
  uploadedFile.value = null
  uploading.value = false
}

const confirm = () => {
  if (!uploadedFile.value) {
    ElMessage.warning('请先上传文件！')
    return
  }
  
  activeNodes.value.forEach(node => {
    // 获取当前节点的文本内容
    let currentText = node.getData('text') || ''
    
    // 创建文件链接HTML
    const fileLink = `<a href="${uploadedFile.value.url}" download="${uploadedFile.value.name}" style="color: #409EFF; text-decoration: underline;">${uploadedFile.value.name}</a>`
    
    // 如果当前文本为空，直接设置为文件链接
    // 如果有文本，在文本后添加文件链接
    const newText = currentText ? `${currentText}<br/>${fileLink}` : fileLink
    
    // 设置节点文本（富文本格式）
    node.setData({
      text: newText,
      richText: true,
      fileUrl: uploadedFile.value.url,
      fileName: uploadedFile.value.name
    })
  })
  
  cancel()
}
</script>

<style lang="less" scoped>
.nodeFileDialog {
  .fileUploadContainer {
    min-height: 120px;
    
    .uploadArea {
      text-align: center;
      padding: 20px;
      
      .tip {
        margin-top: 10px;
        color: #999;
        font-size: 12px;
      }
    }
    
    .fileInfo {
      padding: 20px;
      border: 1px solid #e4e7ed;
      border-radius: 4px;
      
      .fileName {
        font-size: 16px;
        margin-bottom: 8px;
        
        i {
          margin-right: 8px;
          color: #409EFF;
        }
      }
      
      .fileUrl {
        font-size: 12px;
        color: #999;
        margin-bottom: 10px;
        word-break: break-all;
      }
    }
  }
}
</style>